﻿using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Willow.WebApplication.Hubs
{
    public class ChatHub : Hub
    {
        private ChatRoom _chatroom;
        public ChatHub()
            : this(ChatRoom.Instance)
        {
        }
        public ChatHub(ChatRoom chatroom)
        {
            _chatroom = chatroom;
        }

        public void Online(string name, string orgId)
        {
            var connectionId = Context.ConnectionId;
            ChatUser user = new ChatUser() { Name = name, Id = connectionId, OrgId = orgId };
            _chatroom.Online(connectionId, user);
            var allUsers = _chatroom.GetAllUsers().Where(p => p.Id != connectionId);
            //Clients.Caller.onConnected(connectionId, name, allUsers);
            Clients.AllExcept(connectionId).onNewUserConnected(user);
        }

        public IEnumerable<ChatUser> GetUsersByOrg(string orgId)
        {
            var connectionId = Context.ConnectionId;
            var lst= _chatroom.GetAllUsers().Where(p => p.Id != connectionId && p.OrgId == orgId).ToList();
            return lst;
        }

        public void SendPrivateMessage(string toUserId, string message)
        {
            string fromUserId = Context.ConnectionId;
            var toUser = _chatroom.GetUser(toUserId);
            var fromUser = _chatroom.GetUser(fromUserId);
            if (toUser != null && fromUser != null)
            {
                Clients.Client(toUserId).sendPrivateMessage(fromUserId, fromUser.Name, message);
                Clients.Caller.sendPrivateMessage(toUserId, fromUser.Name, message);
            }
        }
        public override System.Threading.Tasks.Task OnDisconnected()
        {
            var connectionId = Context.ConnectionId;
            _chatroom.OffLine(connectionId);
            Clients.All.onUserDisconnected(connectionId);
            return base.OnDisconnected();
        }
    }
}